package cn.iocoder.springboot.lab17.dynamicdatasource.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.iocoder.springboot.lab17.dynamicdatasource.config.MinioConfig;
import cn.iocoder.springboot.lab17.dynamicdatasource.dataobject.*;
import cn.iocoder.springboot.lab17.dynamicdatasource.mapper.HdwaFireServiceMapper;
import cn.iocoder.springboot.lab17.dynamicdatasource.mapper.MyMapper;
import cn.iocoder.springboot.lab17.dynamicdatasource.mapper.OldFireMapper;
import cn.iocoder.springboot.lab17.dynamicdatasource.mapper.PgMapper;
import cn.iocoder.springboot.lab17.dynamicdatasource.util.MinioUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service
@Slf4j
public class CommonService {

//    static Map<String, String> CLASS_CODE_MAP = new HashMap<>();
//
//    static Map<String, String> CLASS_CODE_CODE_MAP = new HashMap<>();

    static {
//        CLASS_CODE_MAP.put("ACAT", "HVAC");
//        CLASS_CODE_MAP.put("ACCHHE", "HHE");
//        CLASS_CODE_MAP.put("ACCHWT", "HWT");
//
//        CLASS_CODE_CODE_MAP.put("AHUequipFreqSet", "supplyFanFreqSet");
//        CLASS_CODE_CODE_MAP.put("ACCCdCDPBV_DistributorCollectorBypassValveOpening", "distributorCollectorBypassOpening");
//        CLASS_CODE_CODE_MAP.put("ACCCwD_lengyuanshangyixiaoshinenghao", "lastHourAccE");
//        CLASS_CODE_CODE_MAP.put("ACCCwD_shiwaihanzhi", "shiwaihanzhi");
//        CLASS_CODE_CODE_MAP.put("CO2SwD_co2nongdu", "concentrate");
//        CLASS_CODE_CODE_MAP.put("COSwD_co2nongdu", "concentrate");
//        CLASS_CODE_CODE_MAP.put("DWHPSPSwD_shenghuogeishuigongshuiyaliceliangzhi", "press");
//        CLASS_CODE_CODE_MAP.put("WEEMeMCU_MonthlyAccE", "monthlyAccE");
//        CLASS_CODE_CODE_MAP.put("WEEMeMCU_YearlyAccE", "yearlyAccE");
//        CLASS_CODE_CODE_MAP.put("WEEMeMCU_DailyAccE", "dailyAccE");
//        CLASS_CODE_CODE_MAP.put("CHUSCwD_yasuojiqidongcishu", "accCompressStartTimes");
//        CLASS_CODE_CODE_MAP.put("LFAHUequipFreqSet", "supplyFanFreqSet");
//
//        CLASS_CODE_CODE_MAP.put("CHUSCcondInTemp", "condWaterInTemp");
//        CLASS_CODE_CODE_MAP.put("CHUSCcondOutTemp", "condWaterOutTemp");
//        CLASS_CODE_CODE_MAP.put("CHUSCwD_yasuojiqidongcishu", "accCompressStartTimes");
//        CLASS_CODE_CODE_MAP.put("FAUwD_co2nongdu", "returnAirCO2");
//        CLASS_CODE_CODE_MAP.put("FAUwaterValveOpening", "chillWaterValveOpening");
//        CLASS_CODE_CODE_MAP.put("FAUwaterValveOpeningSet", "chillWaterValveOpeningSet");
//        CLASS_CODE_CODE_MAP.put("AHUwaterValveOpeningSet", "chillWaterValveOpeningSet");
//        CLASS_CODE_CODE_MAP.put("AHUwaterValveOpening", "chillWaterValveOpening");
//        CLASS_CODE_CODE_MAP.put("DWHPSPSwD_shenghuogeishuigongshuiyaliceliangzhi", "press");
//        CLASS_CODE_CODE_MAP.put("CO2SwD_co2nongdu", "returnAirCO2");

    }

    @Autowired
    OldFireMapper oldFireMapper;
    @Autowired
    HdwaFireServiceMapper hdwaFireServiceMapper;
    @Autowired
    private MyMapper myMapper;
    @Autowired
    private PgMapper pgMapper;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private MinioConfig configuration;

    private CommonService self() {
        return (CommonService) AopContext.currentProxy();
    }

    public void init() {

    }

    /**
     * 同步系统和系统点位
     */
    public void syncSystem(String projectId) {
        //根据广场id查询（实施端）所有系统
        List<PgObjectDO> pgObjectDOS = pgMapper.selectSystem(projectId);
        for (PgObjectDO pgObjectDO : pgObjectDOS) {
            String newClassCode = myMapper.getAdmConstructionJidianMapping("1", pgObjectDO.getClassCode());
            String classCode = StringUtils.isEmpty(newClassCode) ? pgObjectDO.getClassCode() : newClassCode;
            pgObjectDO.setClassCode(classCode);
            MySystemDO mySystemDO = new MySystemDO();
            BeanUtils.copyProperties(pgObjectDO, mySystemDO);
            //组装数据插入（项目构建-机电）系统
            myMapper.addSystem(mySystemDO);
            save(pgObjectDO);
        }

    }

    /**
     * 同步设备点位
     */
    public void syncEquipment(String projectId) {
        //根据广场id查询（实施端）所有设备
        List<PgObjectDO> pgObjectDOS = pgMapper.selectEquip(projectId);
        for (PgObjectDO pgObjectDO : pgObjectDOS) {
            //组装数据插入（项目构建-机电）设备
            String newClassCode = myMapper.getAdmConstructionJidianMapping("1", pgObjectDO.getClassCode());
            String classCode = StringUtils.isEmpty(newClassCode) ? pgObjectDO.getClassCode() : newClassCode;
            pgObjectDO.setClassCode(classCode);
            save(pgObjectDO);
        }
    }

    /**
     * 同步infos中的点位
     *
     * @param projectId 项目id
     * @param wdCode    实施端叫wdCode，云端统一为classCode
     * @param code
     */
    public void syncInfosParam(String projectId, String wdCode, String code) {
        //根据广场id查询（实施端）所有系统
        List<PgParamDO> pgParamDOS = pgMapper.selectInfosParam(projectId, wdCode, code);
        Map<String, String> infoPointMap = myMapper.getInfoPointId(projectId, wdCode, code);
        if (ObjectUtils.isEmpty(infoPointMap)) {
            log.error("绑定点位异常，classCode:{},paramName:{},infoPointMap:{}", wdCode, code, infoPointMap);
            return;
        }
        for (PgParamDO pgParamDO : pgParamDOS) {
            //组装数据插入（项目构建-机电）系统
            MyParamDo myParamDo = new MyParamDo();
            myParamDo.setId(pgParamDO.getEquipmentId() + "-" + infoPointMap.get("gnh"));
            myParamDo.setInfoPointId(infoPointMap.get("id"));
            myParamDo.setProjectId(projectId);
            myParamDo.setObjectId(pgParamDO.getEquipmentId());
            myParamDo.setOutParamId(pgParamDO.getOutParamId());
            myMapper.addParam(myParamDo);
        }
    }

    /**
     * 保存
     *
     * @param pgObjectDO
     */
    private void save(PgObjectDO pgObjectDO) {
        String collectCode = pgObjectDO.getCollectCode();
        String projectId = pgObjectDO.getProjectId();
        //查询（项目构建-机电）的采集器
        Map<String, String> collectCodeMap = myMapper.getInfoPointId(projectId, pgObjectDO.getClassCode(), "collectorCode");
        if (!StringUtils.isEmpty(collectCode) && !ObjectUtils.isEmpty(collectCodeMap)) {
            MyParamDo myParamDo = new MyParamDo();
            myParamDo.setId(pgObjectDO.getId() + "-" + collectCodeMap.get("gnh"));
            myParamDo.setInfoPointId(collectCodeMap.get("id"));
            myParamDo.setProjectId(projectId);
            myParamDo.setOutParamId(collectCode);
            myParamDo.setObjectId(pgObjectDO.getId());
            //插入采集器点位
            myMapper.addParam(myParamDo);
        } else {
            log.error("采集器异常，classCode:{},collectCodeMap:{}", pgObjectDO.getClassCode(), collectCodeMap);
        }

        String name = pgObjectDO.getName();
        //查询（项目构建-机电）的慧云总部名称
        Map<String, String> huiyunzongbumingchengMap = myMapper.getInfoPointId(projectId, pgObjectDO.getClassCode(), "huiyunzongbumingcheng");
        if (!StringUtils.isEmpty(name) && !ObjectUtils.isEmpty(huiyunzongbumingchengMap)) {
            MyParamDo myParamDo = new MyParamDo();
            myParamDo.setId(pgObjectDO.getId() + "-" + huiyunzongbumingchengMap.get("gnh"));
            myParamDo.setInfoPointId(huiyunzongbumingchengMap.get("id"));
            myParamDo.setProjectId(projectId);
            myParamDo.setOutParamId(name);
            myParamDo.setObjectId(pgObjectDO.getId());
            //插入慧云总部名称点位
            myMapper.addParam(myParamDo);
        } else {
            log.error("慧云总部名称异常，classCode:{},name:{},huiyunzongbumingchengMap:{}", pgObjectDO.getClassCode(), name, huiyunzongbumingchengMap);
        }

        //处理设备点位
        List<PgParamDO> pgParamDOS = pgMapper.selectParam(pgObjectDO.getId());
        for (PgParamDO pgParamDO : pgParamDOS) {
            String newCode = myMapper.getAdmConstructionJidianMapping("2", pgObjectDO.getClassCode() + pgParamDO.getParamName());
            String code = StringUtils.isEmpty(newCode) ? pgParamDO.getParamName() : newCode;
            Map<String, String> infoPointMap = myMapper.getInfoPointId(projectId, pgObjectDO.getClassCode(), code);
            if (ObjectUtils.isEmpty(infoPointMap)) {
                log.error("绑定点位异常，classCode:{},paramName:{},infoPointMap:{}", pgObjectDO.getClassCode(), code, infoPointMap);
                continue;
            }
            MyParamDo myParamDo = new MyParamDo();
            myParamDo.setId(pgParamDO.getEquipmentId() + "-" + infoPointMap.get("gnh"));
            myParamDo.setInfoPointId(infoPointMap.get("id"));
            myParamDo.setProjectId(projectId);
            myParamDo.setCollectorCode(pgParamDO.getCollectCode());
            myParamDo.setObjectId(pgParamDO.getEquipmentId());
            myParamDo.setOperator(pgParamDO.getOperator());
            myParamDo.setOperatorParam(pgParamDO.getNumberParam());
            myParamDo.setOperatorControl(pgParamDO.getOpratorControl());
            myParamDo.setOperatorStatus(pgParamDO.getOpratorStatus());
            myParamDo.setOutParamId(pgParamDO.getOutParamId());
            myMapper.addParam(myParamDo);
        }
    }

    public int deleteSystemAndObjectParam(String projectId) {
        myMapper.deleteSystem(projectId);
        return myMapper.deleteObjectParam(projectId);
    }

    public int createTable(String projectId) {
        myMapper.deleteSystem(projectId);
        return myMapper.deleteObjectParam(projectId);
    }

    public void copy(String tableName,
                     String keyField,
                     String oldFilePathField,
                     String newFilePathField,
                     String bucketName) {
        bucketName = StringUtils.isEmpty(bucketName) ? configuration.getBucketName() : bucketName;
        List<Map<String, String>> list = oldFireMapper.list(tableName, keyField, oldFilePathField, newFilePathField);
        if (CollectionUtils.isEmpty(list)) {
            log.error("待迁移数据为空");
            return;
        }
        for (Map<String, String> map : list) {
            String key = map.get(keyField);
            try {
                String filePath = map.get(oldFilePathField);
                if (StringUtils.isEmpty(filePath)) {
                    continue;
                }
                ////因为是测试，图片url可以随便搞一个，我从百度随便复制了个图片url
                //filePath = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fnimg.ws.126.net%2F%3Furl%3Dhttp%253A%252F%252Fdingyue.ws.126.net%252F2021%252F0812%252Fc8eb08e2j00qxqd8w0057c0012w00obg.jpg%26thumbnail%3D650x2147483647%26quality%3D80%26type%3Djpg&refer=http%3A%2F%2Fnimg.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651129353&t=f034e15dc07748726fa861080938ec36";
                //建立图片连接
                URL url = new URL(filePath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //设置请求方式
                connection.setRequestMethod("GET");
                //设置超时时间
                connection.setConnectTimeout(3 * 1000);
                //输入流
                InputStream stream = connection.getInputStream();
                byte[] bytes = minioUtils.input2byte(stream);
                String fileId = IdUtil.getSnowflakeNextIdStr();
                String newFileName = fileId + ".png";
                minioUtils.createFile(newFileName, bytes, null);
                //String fileUrl = minioUtils.getFileUrl(bucketName, newFileName);
                SysFileDO multipartFile = new SysFileDO();
                multipartFile.setFileId(fileId);
                multipartFile.setPath(newFileName);
                String md5 = DigestUtil.md5Hex(stream);
                multipartFile.setMd5(md5);
                multipartFile.setFileSystem("minio");
                multipartFile.setFileName(newFileName);
                multipartFile.setAppId("appId");
                multipartFile.setBucketName(bucketName);
                multipartFile.setTotalBytes(bytes.length);
                multipartFile.setExt(".png");
                multipartFile.setDelStatus("undeleted");
                multipartFile.setCreateUser("system");

                // 组装jpass图片组件返回值
                List<Map> arrayList = new ArrayList<>();
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("fileId", fileId);
                hashMap.put("size", bytes.length);
                hashMap.put("fileName", newFileName);
                hashMap.put("createUser", null);
                hashMap.put("createTime", new Date());
                arrayList.add(hashMap);
                String str = JSONObject.toJSONStringWithDateFormat(arrayList, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
                //// 如果为图片，则生成图片的缩略图
                //sysFileServiceImpl.handImage(".png", bytes, operator, multipartFile, fileModel.getRelPath());
                //
                //sysFileServiceImpl.save(multipartFile);
                //
                ////发送文件转pdf消息中间件处理
                //if (isConvertOffice) {
                //    SysFileDO temp = new SysFileDO();
                //    temp.setFileId(multipartFile.getFileId());
                //    temp.setPath(multipartFile.getPath());
                //    temp.setFileSystem(multipartFile.getFileSystem());
                //    temp.setExt(multipartFile.getExt());
                //    convertOffice(temp);
                //}
                hdwaFireServiceMapper.insert(multipartFile);
                oldFireMapper.updateByKey(tableName, keyField, key, newFilePathField, str);
            } catch (Exception e) {
                log.error("迁移主键:{}数据异常", key, e);
            }
        }


    }
}
